<template>
  <div>
    <div v-show="!selectChildData.id" class="children_content">
      <div class="add_btns_box">
        <div class="box_left">
          <div v-if="props.rowData.id" class="go-back" @click="emit('back')">
            <Icon type="md-arrow-round-back" size="20" />
            返回
          </div>
          <div v-if="props.rowData.id" class="title">{{ props.rowData.name }} 字典项 ({{ total }})
          </div>
          <div v-else class="title">系统数据字典列表 ({{ total }})</div>
        </div>
        <div class="box_right">
          <Space>
            <Button type="primary" @click="handleEdit()" icon="md-add">创建新字典项</Button>
          </Space>
        </div>
      </div>

      <div class="content_table">
        <TemplateTable ref="tableRef" :data="tableData" :columns="tableColumns" :loading="loading"
          :height="tableHeight" :page="pageIndex" :page-size="pageSize" :total="total" border="none"
          size="small" stripe @link-click="handleLinkClick" @page-change="handlePageChange">
        </TemplateTable>
      </div>
    </div>

    <dictionary-template v-if="selectChildData.id" :rowData="selectChildData"
      @back="selectChildData = {}" />

    <EditDialog ref="editDialogRef" v-if="showDialog && props.rowData.id" :rowData="rowData"
      @cancel="handleDialogCancel" @submit="handleDialogSubmit" />

    <ParentEditDialog ref="editDialogRef" v-if="showDialog && !props.rowData.id"
      @cancel="handleDialogCancel" @submit="handleDialogSubmit" />
  </div>
</template>

<script>
export default {
  name: 'DictionaryTemplate'
}
</script>
<script setup>
import { ref, onMounted, getCurrentInstance, inject, watch, nextTick } from 'vue'
import { Message } from 'view-ui-plus'
import moment from 'moment'

import { dictionary } from '@/api/modules/modelSetting'

import { CTYPE_OPTIONS, ICON_TYPE_OPTIONS } from '@/util/conf'

import EditDialog from './components/EditDialog.vue'
import ParentEditDialog from './components/ParentEditDialog.vue'

const { proxy } = getCurrentInstance()
// 屏幕高度
const screenHeight = inject('screenHeight')
// 搜索组件高度
const searchHeight = ref(null)
// 表格高度
const tableHeight = ref(0)
// 监听 screenHeight 的变化
watch(
  screenHeight,
  newHeight => {
    if (searchHeight.value) {
      tableHeight.value = newHeight - searchHeight.value - 245
    } else {
      tableHeight.value = newHeight - 245
    }
  },
  { immediate: true }
)

const emit = defineEmits(['back'])

const props = defineProps({
  rowData: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

const pageIndex = ref(1)
const pageSize = 20
const total = ref(0)

// 是否显示对话框
const showDialog = ref(false)
const editDialogRef = ref(null)

// 列表数据
const tableData = ref([])

// 加载状态
const loading = ref(false)

const getColumnsOptions = () => {
  const colums = [
    { title: '名称', field: 'name', type: 'link', minWidth: 240 },
    { title: '代码', field: 'code', minWidth: 300 }
  ]

  if (props.rowData.id) {
    colums.push(
      ...[
        { title: '英文名称', field: 'usname', minWidth: 140 },
        { title: '繁体名称', field: 'tcname', minWidth: 140 },
        { title: '图标', field: 'iconstr', minWidth: 140 },
        { title: '显示代码', field: 'discode', icon: true, minWidth: 140 },
        { title: '序号', field: 'sortindex', minWidth: 140 }
      ]
    )
  } else {
    colums.push(
      ...[
        {
          title: '系统字典',
          field: 'ctype',
          minWidth: 100,
          formatter: ({ row }) => {
            const rowCtypeData = [...CTYPE_OPTIONS, ...ICON_TYPE_OPTIONS].find(item => item.value === row.ctype)
            return rowCtypeData?.label
          }
        },
        { title: '说明', field: 'description', minWidth: 240 }
      ]
    )
  }

  colums.push({
    title: '创建时间',
    field: 'createTime',
    minWidth: 140,
    formatter: ({ row }) => {
      return row.createtime ? moment(row.createtime).format('YYYY-MM-DD HH:mm:ss') : ''
    }
  })

  if (props.rowData.id) {
    colums.push({ title: '租户', field: 'tenant', icon: true, minWidth: 140 })
  }

  return [
    ...colums,
    {
      title: '操作',
      type: 'action',
      width: 140,
      fixed: 'right',
      actions: [
        {
          text: '编辑',
          onClick: row => handleEdit(row.id)
        },
        {
          text: '删除',
          type: 'del',
          onClick: row => handleDelete(row)
        }
      ]
    }
  ]
}

const tableColumns = ref(getColumnsOptions())

const getPageData = reset => {
  if (reset) {
    pageIndex.value = 1
  }

  loading.value = true

  const { id } = props.rowData
  dictionary.page({
    query: {
      p: pageIndex.value,
      ps: pageSize
    },
    data: {
      id
    }
  })
    .then(({ data }) => {
      tableData.value = data?.topicList || []
      total.value = data?.totalElements || 0
    })
    .finally(() => {
      loading.value = false
    })
}

const selectChildData = ref({})
const handleLinkClick = data => {
  selectChildData.value = data.row
}

const handleEdit = id => {
  showDialog.value = true
  nextTick(() => {
    editDialogRef.value.initDialog(id)
  })
}

const handleDelete = row => {
  proxy.$Modal.confirm({
    mask: false,
    title: '警告',
    content: '<p>是否删除该数据?</p>',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      await dictionary.delete({
        data: {
          id: row.id
        }
      })
      Message.success('删除成功')
      getPageData(true)
    }
  })
}

// 处理对话框取消
const handleDialogCancel = () => {
  showDialog.value = false
}

// 处理对话框提交
const handleDialogSubmit = () => {
  showDialog.value = false
  // 刷新数据列表
  getPageData(true)
}

// 处理页码变化
const handlePageChange = page => {
  pageIndex.value = page
  getPageData()
}

onMounted(() => {
  getPageData()
})
</script>

<style scoped lang="scss">
.box_left {
  display: flex;
  align-items: center;
  .go-back {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: bold;
    margin-right: 16px;
    cursor: pointer;
    &:hover {
      opacity: 0.9;
    }
  }
}
</style>